package com.cman777.springc.sample.config.ratelimit;


import com.cman777.springc.ratelimiter.RateLimiterClient;
import com.cman777.springc.ratelimiter.alg.AlgFactory;
import com.cman777.springc.ratelimiter.alg.storage.RedissonStorageAdapter;
import com.cman777.springc.ratelimiter.collector.ServletCollector;
import com.cman777.springc.ratelimiter.collector.ServletCollectorRegistry;
import com.cman777.springc.ratelimiter.interceptor.ServletInterceptor;
import com.cman777.springc.ratelimiter.rule.RateRuleImporter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author chenzhicong
 * @time 2020/9/18 16:35
 */
@Configuration
@EnableScheduling
public class RateLimitClientConfig {
    @Autowired
    private RateLimiterClient rateLimiterClient;

    @Bean
    public ServletCollectorRegistry servletCollectorRegistry(@Qualifier("COMMON_COLLECTOR") ServletCollector servletCollector) {
        ServletCollectorRegistry servletCollectorRegistry = new ServletCollectorRegistry();
        servletCollectorRegistry.registerServletCollector("COMMON_COLLECTOR", servletCollector);
        return servletCollectorRegistry;
    }

    @Bean
    @ConditionalOnBean(ServletCollectorRegistry.class)
    public RateLimiterClient rateLimiterClient(RateRuleImporter rateRuleImporter, ServletCollectorRegistry servletCollectorRegistry, RedissonClient redissonClient) {
        this.rateLimiterClient = new RateLimiterClient(rateRuleImporter, servletCollectorRegistry, new AlgFactory(new RedissonStorageAdapter(redissonClient)));
        return this.rateLimiterClient;
    }
    @ConditionalOnBean(RateLimiterClient.class)
    @Bean
    public WebMvcConfigurer rateLimitIntercepterConfig(){
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new ServletInterceptor(rateLimiterClient));
            }
        };
    }



}
